package com.sam.c_proxy;

import com.sam.service.IUserService;
import com.sam.service.impl.UserServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class UserServiceProxyFactory implements InvocationHandler {

    public UserServiceProxyFactory(IUserService iUserService) {
        super();
        this.iUserService = iUserService;
    }

    private IUserService iUserService;

    public IUserService getUserServiceProxy(){
        //生成动态代理
        IUserService usProxy = (IUserService) Proxy.newProxyInstance(UserServiceProxyFactory.class.getClassLoader(), UserServiceImpl.class.getInterfaces(), this);

        //返回
        return usProxy;

    }

    /**
     *
     * @param proxy     当前代理对象
     * @param method    当前调用的方法
     * @param args      当前调用方法的参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("2打开事务...");
        Object invoke = method.invoke(iUserService, args);
        System.out.println("2提交事务...");
        return invoke;
    }
}
